package com.qihoo.finance.backup.writer;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.qihoo.finance.backup.Result;
import com.qihoo.finance.backup.ResultUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;

import java.util.List;

public class MongoBackWriter implements BackWriter {

    private static final Logger logger = LogManager.getLogger(MongoBackWriter.class);

    private MongoClient mongoClient;

    private String database;

    private String collection;

    private MongoCollection<Document> mongoCollection;

    public void setDatabase(String database) {
        this.database = database;
    }

    public void setCollection(String collection) {
        this.collection = collection;
    }

    public void setMongoClient(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    @Override
    public void connect() {
        try {
            MongoDatabase mongoDatabase = mongoClient.getDatabase(database);
            mongoCollection = mongoDatabase.getCollection(collection);
        } catch (Exception e) {
            logger.error("mongoBackWriter connected exception", e);
            throw new RuntimeException("mongoBackWriter connected exception", e);
        }
    }

    @Override
    public Result write(List<String> rows) {
        String lastRow = null;
        try {
            for (String row : rows) {
                lastRow = row;
                Document parse = Document.parse(row);
                mongoCollection.insertOne(parse);
            }
            return ResultUtils.success();
        } catch (Exception e) {
            logger.error("mongoBackWriter write data exception, lastRow is {}", lastRow, e);
            return ResultUtils.error("E01", "mongoBackWriter write exception", lastRow);
        }
    }

    @Override
    public void close() {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }
}
